/**
 * 导出测试用例（JSON格式）
 *
 * Created by qinmengchao on 2020/09/28.
 */
const TestCase = require('./../mongo/test-case');
const Func = require('./../mongo/function');
const File = require('./../mongo/file');
const defaultSeparator = ':';

/**
 * 收集项目版本的测试用例集合
 * @param {String} projectVersionId 项目版本id
 * @param {String} separator 分隔符
 * @return {Promise}
 */
function collectTests(projectVersionId, separator = defaultSeparator) {
  return new Promise((resolve, reject) => {
    const conditions = { versionId: projectVersionId };
    const functionMap = new Map();
    const fileMap = new Map();
    const tests = {};
    const promises = [
      File.find(conditions),
      Func.find(conditions),
      TestCase.find(conditions),
    ];
    Promise.all(promises)
      .then(([resFiles, resFunctions, resTestCases]) => {
        resFunctions.forEach((func) => {
          const functionId = func._id;// eslint-disable-line no-underscore-dangle
          functionMap.set(functionId.toString(), func);
        });
        resFiles.forEach((file) => {
          const fileId = file._id;// eslint-disable-line no-underscore-dangle
          fileMap.set(fileId.toString(), file);
        });
        resTestCases.forEach((testCase) => {
          if (!functionMap.has(testCase.functionId.toString())) {
            return;
          }
          const func = functionMap.get(testCase.functionId.toString());
          const file = fileMap.get(func.fileId.toString());
          const key = file.path + separator + func.functionName;
          if (tests[key] === undefined) {
            tests[key] = [];
          }
          tests[key].push({
            functionId: testCase.functionId,
            data: testCase.data,
            kind: testCase.kind,
            description: testCase.description,
          });
        });
        resolve(tests);
      })
      .catch(reject);
  });
}

module.exports = {
  collectTests,
};
